#include "app_serial.h"
#include "log/log.h"
#include "stdlib.h"

SerialDevice *app_serial_init(char *filename)
{
    // 初始化一个设备
    Device *device = app_device_init(filename);
    if(device == NULL){
        log_fatal("device init failed");
        return NULL;
    }
    //在设备内存基础上拓展出一个串口设备内存
    SerialDevice *serial = realloc(device,sizeof(SerialDevice));
    if(serial == NULL){
        log_fatal("serial device init failed"); 
        return NULL;
    }
    if(app_serial_setBaudrate(serial, BR_115200)!=0){
        log_fatal("serial set baudrate failed");
        app_device_close(device);
        return NULL;
    }
    if(app_serial_setParity(serial, Parity_None)!=0){
        log_fatal("serial set parity failed");
        app_device_close(device);
        return NULL;
    }
    if(app_serial_setStopBits(serial, StopBits_1)!=0){
        log_fatal("serial set stopbits failed");
        app_device_close(device);
        return NULL;
    }

    tcflush(serial->super.fd, TCIOFLUSH);
    return serial;
}   

int app_serial_setBaudrate(SerialDevice *serial, BraudRate baud_rate)
{
    struct termios termios;
    if(tcgetattr(serial->super.fd, &termios)!=0){
        log_error("tcgetattr error");
        return -1;
    }
    if(tcsetattr(serial->super.fd, TCSAFLUSH, &termios)!=0){
        log_error("tcsetattr error");
        return -1;
    }
}

int app_serial_setParity(SerialDevice *serial, BraudRate baud_rate)
{
    struct termios termios;
    if(tcgetattr(serial->super.fd, &termios)!=0){
        log_error("tcgetattr error");
        return -1;
    }
    if(tcsetattr(serial->super.fd, TCSAFLUSH, &termios)!=0){
        log_error("tcsetattr error");
        return -1;
    }
}
int app_serial_setStopBits(SerialDevice *serial, BraudRate baud_rate)
{
    struct termios termios ;
    if(tcgetattr(serial->super.fd, &termios)!=0){
        log_error("tcgetattr error");
        return -1;
    }
    if(tcsetattr(serial->super.fd, TCSAFLUSH, &termios)!=0){
        log_error("tcsetattr error");
        return -1;
    }
}